import Vue from 'vue'
import router from './router'
import store from './store'

import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style
// import notification from 'ant-design-vue/es/notification'
import { setDocumentTitle, domTitle } from '@/utils/domUtil'
import { getQueryString } from '@/utils/common'
import { ACCESS_TOKEN } from '@/store/mutation-types'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = [] // no redirect whitelist
const errorPages = ['exception-404', 'exception-403'] // 异常页面

router.beforeEach(async (to, from, next) => {
  console.log(to, from)
  NProgress.start() // start progress bar

  if (errorPages.includes(to.name)) {
    return next()
  }
  if (to.meta && to.meta.title) {
    setDocumentTitle(to.meta.title + ' - ' + domTitle)
  }

  // 获取统一认证登录地址
  const { authUrl } = store.getters
  if (!authUrl) {
    const url = await store.dispatch('GetAuthUrl')
    if (!url) {
      return next({ path: '/404', query: {} })
    }
  }

  // 验证地址栏传递的 code 信息
  const code = getQueryString('code')
  if (code) {
    const { href } = window.location
    const url = href.replace('?code=' + code + '&state=STATE', '')
    await store.dispatch('Login', code).then(res => {
      next(false)
      location.replace(url)
    }).catch(res => {
      store.dispatch('Logout', { isReqLogOut: false, path: url })
    })
    return
  }

  if (whiteList.includes(to.name)) {
    return next()
  }

  const token = Vue.ls.get(ACCESS_TOKEN)
  if (token) {
    next()
    // const { permission, user } = store.state
    // if (permission.addRouters.length === 0) {
    //   store.dispatch('GenerateRoutes', { id: user.info.id }).then(routers => {
    //     // 动态添加可访问路由表
    //     router.addRoutes(routers)
    //     // 请求带有 redirect 重定向时，登录自动重定向到该地址
    //     const redirect = decodeURIComponent(from.query.redirect || to.path)
    //     if (to.path === redirect) {
    //       // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
    //       next({ ...to, replace: true })
    //     } else {
    //       // 跳转到目的路由
    //       next({ path: redirect })
    //     }
    //   }).catch(error => {
    //     errorNotice(error)
    //     return next({ path: '/403', query: {} })
    //   })
    // } else {
    //   next()
    // }
  } else {
    store.dispatch('Logout', { isReqLogOut: false })
    NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})

// 菜单获取失败错误提示信息
// function errorNotice (error) {
//   NProgress.done()
//   notification.warning({
//     key: 'request-error',
//     message: error && error.message || '请联系管理员分配资源！！！'
//   })
// }
